package com.tanjun.web.annotation.aspect;

import com.tanjun.web.annotation.HasLogin;
import com.tanjun.web.service.LoginUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
@Slf4j
public class HasLoginAspect {
    /**
     * 登录验证
     * @param joinPoint
     * @return
     */
    @Around("@within(com.tanjun.web.annotation.HasLogin)||@annotation(com.tanjun.web.annotation.HasLogin)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            // 1. 检查方法上是否有 @Log
            HasLogin methodHasLogin = method.getAnnotation(HasLogin.class);
            if (methodHasLogin != null) {
                log.info("method has login, method name:{}", method.getName());
            }
            else {
                HasLogin classHasLogin = joinPoint.getTarget().getClass().getAnnotation(HasLogin.class);
                if (classHasLogin != null) { // 避免重复处理
                    log.info("class has login,class name: {}", signature.getClass().getName());
                }
            }
            LoginUserUtil.getLoginUserInfo();
            // 执行目标方法
            return joinPoint.proceed();

    }
}
